package cn.mcch.investigator.model;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import cn.mcch.investigator.utils.ConstantUtil;
import cn.mcch.investigator.utils.MD5UTils;
import cn.mcch.investigator.utils.ToastUtils;
import okhttp3.Call;
import okhttp3.Request;

/**
 * 网络请求基类
 *
 * @author Cao Mingming
 * @date 2016-5-4 11:51:21
 */
public abstract class BaseRequest {

    /**
     * 网络请求结果标记
     */
    public boolean result;

    /**
     * 网络请求回调
     */
    private NetCallBack mCallBack;

    private SimpleDateFormat simpleDateFormat;

    /**
     * @param id
     * @param service
     * @param params
     */
    public void request(int id, String service, Map<String, String> params) {

        if (mCallBack == null) {
            mCallBack = new NetCallBack();
        }
        if (simpleDateFormat == null) {
            simpleDateFormat = new SimpleDateFormat("yyyyMMddHH");
        }
        OkHttpUtils.post().url(getURL(service)).tag(this).id(id).params(params).build().execute(mCallBack);
    }

    /**
     * 拼接url
     * @param service
     * @return
     */
    private String getURL(String service) {
        StringBuilder stringBuilder = new StringBuilder(ConstantUtil.URL);
        stringBuilder.append(service);
        stringBuilder.append("&token=");
        stringBuilder.append(MD5UTils.md5(ConstantUtil.KEY + simpleDateFormat.format(new Date(System.currentTimeMillis()))));
        return stringBuilder.toString();
    }

    /**
     * 取消网络请求
     */
    public void cancelTag() {
        OkHttpUtils.getInstance().cancelTag(this);
    }

    /**
     * 网络请求回调类
     *
     * @author Administrator
     */
    private class NetCallBack extends StringCallback {

        @Override
        public void onBefore(Request request, int id) {
            BaseRequest.this.onBefore(id);
        }

        @Override
        public void onAfter(int id) {
            BaseRequest.this.onAfter(result, id);
        }

        @Override
        public void onError(Call arg0, Exception arg1, int id) {
            result = false;
            ToastUtils.showToast("请求服务器失败，请检查网络！");

        }

        @Override
        public void onResponse(String json, int id) {
            BaseRequest.this.onResponse(json, id);
        }
    }

    public abstract void onAfter(boolean result, int id);

    public abstract void onBefore(int id);

    public abstract void onResponse(String json, int id);
}
